from http.server import HTTPServer, BaseHTTPRequestHandler
import json
import socket
import time
import re
import core

import urllib.parse


# import urllib


# ----------------------------------------------------------
def getIP():
    # 获取本机计算机名称
    hostname = socket.gethostname()
    # 获取本机ip
    ip = socket.gethostbyname(hostname)
    return ip


host = (getIP(), 2333)


# ----------------------------------------------------------
class Resquest(BaseHTTPRequestHandler):
    def do_GET(self):
        # print(self.path)
        result = {'err': 'target error'}
        if re.search('spider\?target=', self.path):
            qs = {}
            for key, value in dict(urllib.parse.parse_qsl(self.path.split("?")[1], True)).items():
                qs.update({key: value})
            target = qs['target']

            if re.search('\.', target):
                spider = core.init(target)
                result = spider['base']
                if 'detail' in qs:
                    result = spider

        self.send_response(200)
        self.send_header('Content-type', 'application/json')
        self.end_headers()
        self.wfile.write(json.dumps(result).encode())


# ----------------------------------------------------------
server = HTTPServer(host, Resquest)
print("Starting server, listen at: %s:%s" % host)
server.serve_forever()
